package org.dreamwork.android.websocket.impls.okhttp_3_6_0;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.WebSocket;
import okio.ByteString;
import org.dreamwork.android.websocket.IWebSocketLibrary;
import org.dreamwork.android.websocket.IWebSocketListener;

import java.util.concurrent.TimeUnit;

/**
 * Created by game on 2017/3/6
 */
public final class OkHttpLibrary implements IWebSocketLibrary {
    private IWebSocketListener listener;
    private WebSocket          socket;

    private static final String USER_AGENT =
            "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36";

    public OkHttpLibrary (IWebSocketListener listener) {
        this.listener = listener;
    }

    @Override
    public void connect (String url) {
        OkHttpClient client = new OkHttpClient.Builder ()
                .connectTimeout (30, TimeUnit.SECONDS)
                .readTimeout    (30, TimeUnit.SECONDS)
                .writeTimeout   (30, TimeUnit.SECONDS)
                .build ();
        Request request = new Request.Builder ()
                .url (url)
                .addHeader ("User-Agent", USER_AGENT)
                .build ();
        socket = client.newWebSocket (request, new OkHttpWebSocketListenerDelegate (listener));
    }

    @Override
    public void send (String message) {
        socket.send (message);
    }

    @Override
    public void send (byte[] message) {
        ByteString buff = ByteString.of (message, 0, message.length);
        socket.send (buff);
    }

    @Override
    public void close () {
        if (socket != null) {
            socket.cancel ();
            socket.close (1000, null);
        }
    }
}